<?php
namespace control;/*
*公积金核算类
*/

class providentFundClass extends adIndexClass
{
    private const title = '公积金核算';
    private const page = 'providentFund';
    private const pageRecord = 'providentFundRecord';
    private const table = 'provident_fund';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'deductionSearch':
                $tr = [
                    'department'      => [
                        'name'  => L('salary.table.bu_men'),
                        'width' => 150,
                    ],
                    'job' => [
                        'name'  => L('salary.table.zhi_wei'),
                        'width' => 150,
                    ],
                    'name'  => [
                        'name'  => L('salary.table.yuan_gong'),
                        'width' => 150,
                    ],
                    'month'         => [
                        'name'  => L('salary.table.jiao_na_yue_fen'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'companyFund'          => [
                        'name'  => L('salary.table.companyPart')."(" . static::$unit . ")",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'personFund'    => [
                        'name'  => L('salary.table.personalPart')."(" . static::$unit . ")",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'decMoney'    => [
                        'name'  => L('salary.table.accountDec')."(" . static::$unit . ")",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'total'    => [
                        'name'  => L('salary.table.total')."(" . static::$unit . ")",
                        'width' => 150,
                    ],
                    'text'    => [
                        'name'  => L('salary.table.bei_zhu'),
                        'width' => 200,
                    ]
                ];
                break;
            default:
                $tr = [
                    'department'      => [
                        'name'  => L('salary.table.bu_men'),
                        'width' => 200,
                    ],
                    'job' => [
                        'name'  => L('salary.table.zhi_wei'),
                        'width' => 200,
                    ],
                    'name'  => [
                        'name'  => L('salary.table.yuan_gong'),
                        'width' => 200,
                    ],
                    'companyFund'         => [
                        'name'  => L('salary.table.companyPart')."(" . static::$unit . ")",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'personalFund'          => [
                        'name'  => L('salary.table.personalPart')."(" . static::$unit . ")",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'decText'    => [
                        'name'  => L('salary.table.zhkk')."(" . static::$unit . ")",
                        'width' => 200,
                    ],
                    'text'    => [
                        'name'  => L('salary.table.bei_zhu'),
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function deductionOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('salary.table.xing_ming') => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    L('salary.table.bu_men') => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                    L('salary.table.jkyf') => text(array("name" => "moon", 'laydate' => ['type' => 'month', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 公积金记录
     *
     */
    public function deduction()
    {
        $html = $this->deductionOptions(false);
        //控件
        $button = "";
        if ($this->power(self::pageRecord, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('salary.table.shan_chu')."</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    public function deductionSearch()
    {
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//员工
        );
        $and = '';
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and stid in (select stid from staff where jobId in (select id from job where departmentId = '{$this->post('departmentId')}')) ";
        }
        if ($this->post('moon')) {
            $timeArr = explode(' ~ ', $this->post('moon'));
            $and .= " and month >='{$timeArr[0]}' and month <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'month desc,id',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("recordForm", "recordId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "recordId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            $job = query('job', " id = '$array[jobId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "department":
                        $department = query('department', " id = '$job[departmentId]'");
                        $row[] = $department['name'];
                        break;
                    case "job":
                        $row[] = $job['name'];
                        break;
                    case "name":
                        $row[] = self::findStaff($array['staffId']);
                        break;
                    case "total":
                        $row[] = $array['companyFund'] + $array['personFund'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(companyFund),0) as companyFund,ifnull(sum(personFund),0) as personFund,ifnull(sum(decMoney),0) as decMoney",
        ]);
        $total    = [
            'companyFund'      => $totalQuery['companyFund'],
            'personFund'      => $totalQuery['personFund'],
            'decMoney'      => $totalQuery['decMoney'],
            'total'      => $totalQuery['companyFund'] + $totalQuery['personFund'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='recordForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 提交扣款
     * @return bool|string
     */
    public function commitDec()
    {
        $month = date('Y-m', strtotime("-1 month"));
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                L('salary.table.ti_shi') =>L('salary.table.fund_tip'),
            ),
            array(
                L('salary.table.month').'：' => text(array('name' => 'month', 'laydate' => ['type' => 'month'], 'value' => $month))
            ),
        )));
        //返回
        return $this->layer(array("title" => L('salary.table.gjjkk'), "height" => 226, "width" => 600, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 账户扣款编辑
     * @return bool|string
     */
    public function commitDecEdit()
    {
        $listId = $this->post('listId');
        $textArr = $this->post('text');
        $decMoneyArr = $this->post('decMoney');
        $month = $this->post('month');//月份
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('salary.table.fund_edit_permission');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('salary.table.qxzsj');
        } elseif (empty($month)) {
            $json['warn'] = L('salary.table.qxzyf');
        } else {
            $x = 0;
            foreach ($listId as $k => $stid) {
                $record = query(self::table, "month = '$month' and staffId = '$stid'");

                $staff = query('staff', " stid = '$stid'");
                if (empty($record['id'])) {
                    $id = self::getId();
                    $warn = insert(array(
                        "table" => self::table,
                        "field" => [
                            'id' => $id,
                            'staffId' => $stid,
                            'jobId' => $staff['jobId'],
                            'companyFund' => $staff['companyFund'],
                            'personFund' => $staff['personalFund'],
                            'decMoney' => $decMoneyArr[$stid],
                            'text' => $textArr[$stid],
                            'isCommit' => 1,
                            'stid' => $this->control['stid'],
                            'month' => $month,
                            'time' => $this->time
                        ]
                    ));
                } else {
                    $warn = update(array(
                        "table" => self::table,
                        "field" => [
                            'jobId' => $staff['jobId'],
                            'companyFund' => $staff['companyFund'],
                            'personFund' => $staff['personalFund'],
                            'decMoney' => $decMoneyArr[$stid],
                            'text' => $textArr[$stid],
                            'stid' => $this->control['stid'],
                        ],
                        'where' => " id = '$record[id]'"
                    ));
                    $id = $record['id'];
                }
                if ($warn == '新增成功' || $warn == '更新成功') {
                    $x++;
                    //添加日志
                    $text = str_replace(['{{staffName}}','{{name}}','{{month}}','{{id}}'],[$this->control['name'],$staff['name'],$month,$id],L('salary.table.fund_edit'));
                    $this->logText(["type" => self::page, "text" => $text]);
                }
            }
            //返回
            $_SESSION['warn'] = str_replace(['{{x}}'],[$x],L('salary.table.tax_commit_text'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&menu=record&id=all";
        }
        //返回
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('salary.table.xing_ming') => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    L('salary.table.bu_men') => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 查询条件
     *
     * @param string $workFlow
     * @return string
     */
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'commitDec', {})\">".L('clock.table.decMoney')."</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*社保数据-列表页-查询结果*/
    public function homeSearch()
    {
        //当前月份
        $month = date('Y-m');
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//员工
            'workFlow'=>'已复核'
        );
        $and = " and stid not in (select staffId from " . self::table . " where month = '$month') and state in ('试用','转正','留职')";
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and stid in (select stid from staff where jobId in (select id from job where departmentId = '{$this->post('departmentId')}')) ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => " staff", "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['stid']),
            );
            $liButton[] = $this->dominate($dominate);
            $job = query('job', " id = '$array[jobId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "department":
                        $department = query('department', " id = '$job[departmentId]'");
                        $row[] = $department['name'];
                        break;
                    case "job":
                        $row[] = $job['name'];
                        break;
                    case "name":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case "decText":
                        $decText = text(array('name' => "decMoney[$array[stid]]", 'class' => 'text textPrice', 'value' => $array['personalFund']));
                        $row[] = $decText;
                        break;
                    case "text":
                        $text = text(array('name' => "text[$array[stid]]", 'class' => 'text textPrice', 'value' => ''));
                        $row[] = $text;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('salary.table.delProvidentFund');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, recordForm';
                $power = '';
                break;
        }
        if (!$this->power(self::pageRecord, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('job.other.permission_warn'));
            $json = [
                'warn' => 2,
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /*批量删除*/
    public function delete()
    {
        $array = $this->post('recordId') ?? $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('salary.table.nmzbjgjjjldzx');
        } elseif (empty($array)) {
            $json['warn'] = L('salary.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = L('salary.table.sccg');
                $x++;
                $text .= str_replace(['{{name}}', '{{month}}', '{{id}}'], [self::findStaff($info['staffId']), $info['month'], $id], L('salary.table.fund_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('salary.table.fund_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('salary.table.fund_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}
